<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>H5扫码枪-WEB端</title>
<body>
    <div>
       <span>WebSocket Server ws://</span> <input type="text" id="ws_input" /> <input type="button" value="连接" onclick="connectServer()" id="connect_but" >
    </div>
    <div>
        <textarea style="width:496px;height: 100px;margin-top: 5px;" id="ws_textarea"></textarea>
    </div>
    <div id="qr-reader" style="width:500px"></div>
    <div id="qr-reader-results"></div>
</body>
<script src="/html5-qrcode.min.js"></script>
<script>
    function docReady(fn) {
        // see if DOM is already available
        if (document.readyState === "complete"
            || document.readyState === "interactive") {
            // call on next available tick
            setTimeout(fn, 1);
        } else {
            document.addEventListener("DOMContentLoaded", fn);
        }
    }

/*
    docReady(function () {
        var resultContainer = document.getElementById('qr-reader-results');
        var lastResult, countResults = 0;
        function onScanSuccess(decodedText, decodedResult) {
            if (decodedText !== lastResult) {
                ++countResults;
                lastResult = decodedText;
                // Handle on success condition with the decoded message.
                console.log(`Scan result ${decodedText}`, decodedResult);
				resultContainer.value = decodedText;
            }
        }

        var html5QrcodeScanner = new Html5QrcodeScanner(
            "qr-reader", { fps: 10, qrbox: 250 });
        html5QrcodeScanner.render(onScanSuccess);
    });
	*/
	
docReady(function() {
	var lastMessage;
	var codeId = 0;
	function onScanSuccess(decodedText, decodedResult) {
	    console.log('扫描结果decodedText', decodedText);
	    console.log('扫描结果decodedResult', decodedResult);

        /**
         * If you following the code example of this page by looking at the
         * source code of the demo page - good job!!
         * 
         * Tip: update this function with a success callback of your choise.
         */
		if (lastMessage !== decodedText) {
			lastMessage = decodedText;
            printScanResultPretty(codeId, decodedText, decodedResult);
            ++codeId;
            sendMsg(decodedText);
		}
	}
    var qrboxFunction = function(viewfinderWidth, viewfinderHeight) {
        // Square QR Box, with size = 80% of the min edge.
        var minEdgeSizeThreshold = 250;
        var edgeSizePercentage = 0.75;
        var minEdgeSize = (viewfinderWidth > viewfinderHeight) ?
            viewfinderHeight : viewfinderWidth;
        var qrboxEdgeSize = Math.floor(minEdgeSize * edgeSizePercentage);
        if (qrboxEdgeSize < minEdgeSizeThreshold) {
            if (minEdgeSize < minEdgeSizeThreshold) {
                return {width: minEdgeSize, height: minEdgeSize};
            } else {
                return {
                    width: minEdgeSizeThreshold,
                    height: minEdgeSizeThreshold
                };
            }
        }
        return {width: qrboxEdgeSize, height: qrboxEdgeSize};
    }
	let html5QrcodeScanner = new Html5QrcodeScanner(
        "qr-reader", 
        { 
            fps: 10,
            qrbox: qrboxFunction,
            // Important notice: this is experimental feature, use it at your
            // own risk. See documentation in
            // mebjas@/html5-qrcode/src/experimental-features.ts
            experimentalFeatures: {
                useBarCodeDetectorIfSupported: true
            },
            rememberLastUsedCamera: true,
            showTorchButtonIfSupported: true
        });
	html5QrcodeScanner.render(onScanSuccess);
});

/** Ugly function to write the results to a table dynamically. */
function printScanResultPretty(codeId, decodedText, decodedResult) {
	let resultSection = document.getElementById('qr-reader-results');
    let tableBodyId = "scanned-result-table-body";
    if (!document.getElementById(tableBodyId)) {
        let table = document.createElement("table");
        table.className = "styled-table";
        table.style.width = "100%";
        resultSection.appendChild(table);
        let theader = document.createElement('thead');
        let trow = document.createElement('tr');
        let th1 = document.createElement('td');
        th1.innerText = "Count";
        let th2 = document.createElement('td');
        th2.innerText = "Format";
        let th3 = document.createElement('td');
        th3.innerText = "Result";
        trow.appendChild(th1);
        trow.appendChild(th2);
        trow.appendChild(th3);
        theader.appendChild(trow);
        table.appendChild(theader);
        let tbody = document.createElement("tbody");
        tbody.id = tableBodyId;
        table.appendChild(tbody);
    }
    let tbody = document.getElementById(tableBodyId);
    let trow = document.createElement('tr');
    let td1 = document.createElement('td');
    td1.innerText = `${codeId}`;
    let td2 = document.createElement('td');
    td2.innerText = `${decodedResult.result.format.formatName}`;
    let td3 = document.createElement('td');
    td3.innerText = `${decodedText}`;
    trow.appendChild(td1);
    trow.appendChild(td2);
    trow.appendChild(td3);
    tbody.appendChild(trow);
}


    var socket;

    function connectServer(){
        var h5_barcode_gun_socket_ip = localStorage.getItem("h5_barcode_gun_socket_ip");
        if(h5_barcode_gun_socket_ip){
            document.getElementById("ws_input").value = h5_barcode_gun_socket_ip;
        }else{
            h5_barcode_gun_socket_ip = document.getElementById("ws_input").value;
            if(!h5_barcode_gun_socket_ip){
                appendTextarea("请填写WebSocket Server");
                return;
            }

        }

        socket = new WebSocket('ws://'+h5_barcode_gun_socket_ip);
        // socket = new WebSocket('ws://192.168.123.101:2024');
        socket.onopen = function(event){
            appendTextarea("连接WebSocket Server成功!");
            document.getElementById("connect_but").disabled = true;
            localStorage.setItem("h5_barcode_gun_socket_ip", h5_barcode_gun_socket_ip);
        };

        // 监听消息
        socket.onmessage = function(event){
            console.log('Client received a message',event);
            console.log(event.data);
            appendTextarea(event.data);
        };

        // 监听Socket的关闭
        socket.onclose = function(event){

        };

        socket.onerror = function(event) {
            appendTextarea("无法连接到WebSocket Server:" + socket_ip);
        };
    }

    connectServer()

    function sendMsg(msg){
        socket.send(msg);
        appendTextarea("发送消息:" + msg);
    }

    function appendTextarea(text){
        var ws_textarea = document.getElementById("ws_textarea");
        ws_textarea.value = (ws_textarea.value?ws_textarea.value + "\n":"") + text ;
    }

</script>
</head>
</html>